<template>
    <div v-if="showFieldList.length" style="height: calc(100% - 35px)">
        <vxe-table
            ref="resultTable"
            :key="tableKey"
            :auto-resize="true"
            :data="riskResultTable"
            border
            size="mini"
            style="width: 100%; height: 100%"
            height="100%"
            v-loading="calcLoading"
            resizable
            :resizable-config="{ minWidth: '60' }"
            :sort-config="{ sortMethod: customSortMethod, defaultSort: { field: 'thresholdType', order: 'desc' } }"
            show-header-overflow
            :cell-style="getCellStyle"
            @filter-visible="handleFilterChange"
            align="center"
        >
            <vxe-column
                v-for="(item, index) in showFieldList"
                :key="index + item.id"
                :field="item.id"
                :title="item.content"
                :sortable="item.sortable"
                :column-config="{ isHover: true }"
                :row-config="{ isHover: true }"
                :filters="item.filters"
                :filter-method="item.filterMethod"
                :filter-render="{ name: 'FilterInput' }"
                show-overflow
                :min-width="item.minWidth || 120"
            >
                <template
                    #filter="{ $panel, column }"
                    v-if="
                        [
                            'fundCode',
                            'fundNameSt',
                            'assetCode',
                            'assetName',
                            'fundAccountCode',
                            'fundAccountName',
                            'stockCode',
                            'stockNameSt',
                            'entryCode',
                            'entryName',
                        ].includes(item.id)
                    "
                >
                    <div>
                        <el-input
                            ref="searchInput"
                            class="my-input"
                            type="type"
                            v-for="(option, index) in column.filters"
                            :key="index"
                            v-model="option.data"
                            @input="$panel.changeOption($event, !!option.data, option)"
                        />
                    </div>
                </template>
                <template slot-scope="scope">
                    <span v-if="item.id === 'entryType'">{{ entryType[scope.row.entryType] }}</span>
                    <span v-else-if="item.id === 'compareType'">{{ compareDirection[scope.row.compareType] }}</span>
                    <status-tag v-else-if="item.id === 'thresholdType'" :code="scope.row.thresholdType" />
                    <branch-tag v-else-if="item.id === 'branchNum'" :data="scope.row" />
                    <span v-else-if="['investableBalance', 'maxTradable', 'maxTradableMerge'].includes(item.id)">
                        <el-popover
                            v-if="getObjectLength(scope.row[item.id]) && getObjectLength(scope.row[item.id]) > 1"
                            placement="top"
                            trigger="hover"
                        >
                            <div style="padding: 0 10px 10px 0" slot v-for="(value, key, index) in scope.row[item.id]" :key="key">
                                {{ '阀值' + ++index + getShowName(item.id) + ': ' + scope.row[item.id][getParamName(item.id) + index] }}
                            </div>
                            <el-tag slot="reference">{{ getObjectLength(scope.row[item.id]) + '个' + getShowName(item.id) }}</el-tag>
                        </el-popover>
                        <span v-else-if="getObjectLength(scope.row[item.id])" v-for="(value, key) in scope.row[item.id]" :key="key">{{ value }}</span>
                        <span v-else> --</span>
                    </span>
                    <span v-else-if="item.id === 'thresholdValue'">{{
                        scope.row[item.id] != undefined ? numberFormat(scope.row[item.id], scope.row.unit) + unitShow(scope.row.unit) : '--'
                    }}</span>

                    <span v-else-if="item.id === 'calculateValue'">
                        {{
                            WEB_DOCKING === 'CIBFUND' && scope.row[item.id] != undefined
                                ? numberFormatXDAY(scope.row[item.id], scope.row.unit) + unitShow(scope.row.unit)
                                : scope.row[item.id] != undefined
                                ? numberFormat(scope.row[item.id], !scope.row.unit || scope.row.unit == '无' ? 2 : scope.row.unit) +
                                  unitShow(scope.row.unit)
                                : '--'
                        }}
                    </span>
                    <span v-else>{{ scope.row[item.id] || '--' }}</span>
                </template>
            </vxe-column>
        </vxe-table>
        <!-- <el-pagination
                    background
                    @current-change="pageChangeResult"
                    layout=" total, prev, pager, next"
                    :current-page="pageResult.currentPage"
                    :page-size="pageResult.pageSize"
                    :total="pageResult.total"
                >
                </el-pagination> -->
    </div>
</template>
<script lang="ts">
import Invest from '@/common/dict/invest';
import BranchTag from '@/pages/risk-measure/components/branch-tag.vue';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import { numberFormat, sortBy, unitShow, getConfigItem, numberFormatXDAY } from '@/utils/tools';
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import ColumnUtil from '../utils/column-util';
@Component({
    name: 'TrailResult',
    components: {
        StatusTag,
        BranchTag,
    },
})
export default class TrailResult extends Vue {
    @Prop()
    riskResultTable: any[];
    @Prop()
    showFieldList: any[];
    @Prop()
    calcLoading: boolean;
    @Prop()
    tableColumns: any[];
    Invest: any = new Invest(); // 指令相关字典类
    ColumnUtil = new ColumnUtil();

    tableKey: number = 0;
    tableData: any[] = [];
    entryType = {}; // 风险类型字典
    compareDirection = {}; // 比较方向字典
    entryTypeArr: any[] = []; // 风险类型
    ThresholdTypeArr: any[] = []; // 阈值类型

    numberFormat = numberFormat;
    numberFormatXDAY = numberFormatXDAY;
    WEB_DOCKING = getConfigItem('WEB_DOCKING');
    unitShow = unitShow;

    mounted() {
        // 获取风险类型字典
        this.entryType = this.Invest.entryType;
        // 获取比较方向字典
        this.compareDirection = this.Invest.CompareDirection;
        this.entryTypeArr = this.objToArr(this.Invest.entryType);
        this.ThresholdTypeArr = this.objToArr(this.Invest.ThresholdType); // 获取阈值类型数据
    }

    // 转表格筛选下拉框数据
    objToArr(param) {
        let list = [];
        for (let key in param) {
            list.push({ label: param[key], value: key });
        }
        return list;
    }

    handleFilterChange({ column, property, visible, filterList, $event }) {
        console.log({ column, property, visible, filterList, $event });
    }

    customSortMethod({ data, sortList }) {
        const sortItem = sortList[0];
        // 取出第一个排序的列
        const { property, order } = sortItem;
        let YHList = [];
        let NoYHlist = [];
        let list = [];
        let key = /^[a-zA-Z]+$/;
        data.forEach(ele => {
            if (ele.entryCode.match('.*[A-Z]+.*') || ele.entryCode.match('.*[a-z]+.*')) {
                YHList.push(ele);
            } else {
                NoYHlist.push(ele);
            }
        });

        if (order === 'asc' || order === 'desc') {
            if (property === 'entryCode') {
                YHList.sort(this.compare('entryCode'));
                NoYHlist.sort(this.compare('entryCode'));
                list = NoYHlist.concat(YHList);
                if (order === 'desc') {
                    list.reverse();
                }
            } else {
                list = data.slice().sort(sortBy(property, order));
            }
        }
        return list;
    }

    compare(property) {
        return function (a, b) {
            var value1 = a[property];
            var value2 = b[property];
            if (value1.length < 10 && value2.length < 10) {
                var f = '0000000000'; // 10个0
                var aa = f.substring(0, 10 - ('' + value1).length) + value1;
                var bb = f.substring(0, 10 - ('' + value2).length) + value2;
                return aa > bb ? 1 : -1;
            } else {
                return value1 > value2 ? 1 : -1;
            }
        };
    }

    // 获取对象长度
    getObjectLength(obj: any) {
        if (obj) {
            return Object.keys(obj).length;
        } else {
            return 0;
        }
    }

    // 获取可投余量、最大可交易量名称
    getShowName(name: string) {
        if (name == 'investableBalance') {
            return '可投余量';
        } else if (name == 'maxTradable') {
            return '最大可交易量';
        } else if (name == 'maxTradableMerge') {
            return '最大可交易量(汇总)';
        }
    }

    // 获取字段名
    getParamName(name: string) {
        return name == 'investableBalance' ? 'INVESTABLE_BALANCE_' : name == 'maxTradable' ? 'MAX_TRADABLE_' : 'MAX_TRADABLE_';
    }

    getCellStyle({ column }) {
        let value = 'padding: 0; text-align:center';
        let obj = this.ColumnUtil.riskTableColumns.find(item => item.id == column.property);
        if (obj) {
            value = 'padding: 0; text-align: ' + (obj.align || 'left');
        }
        return value;
    }
}
</script>
<style lang="scss" scoped>
.my-input {
    margin: 10px;
    width: 150px;
}
</style>
